#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, os.path, sys
import tempfile

from jujud.jujud import Jujube

from foxglove import log
from foxglove.juserver import CacheServer

#######################################################################

HOST = "127.0.0.1"
PORT = 54344

SERVICE = 'CACHE'

def removeDirs(dir_name) :
    items = os.listdir(dir_name)
    for item in items :
        dir_item = '%s/%s' % (dir_name, item)
        if os.path.isdir(dir_item) :
            removeDirs(dir_item)
        else :
            #log.debug('CONTENT of file %s', dir_item)
            #for line in file(dir_item) :
            #    log.debug('%s', line.strip())
            log.debug('remove file %s', dir_item)
            os.remove(dir_item)
    if os.path.exists(dir_name) :
        log.debug('remove directory %s', dir_name)
        os.removedirs(dir_name)
    # removedirs()

def main(options):
    if options.verbose :
        log.enableDebug()
    else :
        log.disableDebug()

    s = Jujube()
    s.listenTCP(PORT)

    store_dir = tempfile.mkdtemp(suffix='.dir', prefix='cache_')

    server = CacheServer(store_dir)
    s.registerService(SERVICE, server)
    s.run()

    if os.path.exists(store_dir) :
        removeDirs(store_dir)

    # main()

if __name__ == '__main__' :
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
                        help='show detail information')
    parser.add_option("", "--profile", dest="profile", action="store_true", default=False,
                        help='show profile information')
    (options, args) = parser.parse_args()
    if options.profile :
        prof_file = 'prof.echo.txt'
        import cProfile
        cProfile.run("main(options)", prof_file)
        import pstats
        p = pstats.Stats(prof_file)
        #p.sort_stats("time").print_stats()
        p.sort_stats("cumulative").print_stats()
    else :
        main(options)

    import sys
    sys.exit(0)

